/**
 * 
 */
package com.chinamobile.maps.action;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import com.chinamobile.maps.dao.IUsersDAO;
import com.chinamobile.maps.orm.Users;
import com.chinamobile.maps.util.EncryptionMD5;
import com.chinamobile.maps.util.JsonUtil;
import com.chinamobile.maps.util.LoggerUtil;
import com.chinamobile.maps.util.Struts2Util;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * @author FrankWong
 *
 */
public class UsersAction extends ActionSupport {

	private IUsersDAO usersDao = null;
	public final static String DEFAULT_PASSWORD = "mimr2011";
	private JsonConfig jsonConfig;
	public IUsersDAO getUsersDao() {
		return usersDao;
	}

	public void setUsersDao(IUsersDAO usersDao) {
		this.usersDao = usersDao;
	}

	/**
	 * 
	 */
	
	private static final long serialVersionUID = 586196350478577672L;

	public void getUsersList(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			int pageNumber = Integer.parseInt((request.getParameter("pageNumber")));
			int pageSize = Integer.parseInt((request.getParameter("pageSize")));
			List<Users> users = this.usersDao.getUsers();
			int count;
			if(users == null){
				out.print("{\"result\":false}");
				return;
			}else{
				count = users.size();
				List<Users> usersResult = new ArrayList<Users>();
				for (int i = pageSize * (pageNumber - 1); i < count
						&& i < pageSize * pageNumber; i++) {
					if(users.get(i).getRole().equals("ROLE_USER")){
						users.get(i).setRole("一般用户");
					}
					else{
						users.get(i).setRole("系统管理员");
					}
					usersResult.add(users.get(i));
				}
				Map<String, Object> jsonMap = new HashMap<String, Object>();
				jsonMap.put("total", count);
				jsonMap.put("rows", usersResult);
				JSONObject jsonObject = JSONObject.fromObject(jsonMap,JsonUtil.jsonConfig);
				out.print(jsonObject.toString());
				out.flush();
				out.close();
			}
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	
	public void resetPassword(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			int id = Integer.parseInt((request.getParameter("id")));
			Users users = this.usersDao.getUserByID(id);
			users.setPassword(EncryptionMD5.md5.encodePassword(
					DEFAULT_PASSWORD, users.getLoginName()));
			this.usersDao.updateUser(users);
			LoggerUtil.LogWarn(users.getLoginName()+"的密码已经被重置!");
			out.print("{\"result\":true}");
			out.flush();
			out.close();

		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	
	public void deleteUser(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			int id = Integer.parseInt((request.getParameter("id")));
			Users user = this.usersDao.getUserByID(id);
			//System.out.print(id);
			this.usersDao.delUser(id);
			LoggerUtil.LogWarn("删除用户:"+user.getLoginName());
			out.print("{\"result\":true}");
			out.flush();
			out.close();

		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	
	public void addUser(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			String loginName = String.valueOf(request.getParameter("loginName"));
			String id  = String.valueOf(request.getParameter("id"));
			if(this.usersDao.getUserByName(loginName) != null && id=="null"){
				out.print("{\"result\":\"3\"}");
				out.flush();
				out.close();
				return;
			}
			String fullName = String.valueOf(request.getParameter("fullName"));
			String role = String.valueOf(request.getParameter("role"));
			if( role.equals("系统管理员")){
				role = "ROLE_ADMIN";
			}else{
				role = "ROLE_USER";
			}
			Users user = new Users();
			if(id == null || id.equals("null")){
				user.setCreatedAt(new Date());
				user.setUpdatedAt(new Date());
				user.setFullName(fullName);
				user.setLoginName(loginName);
				user.setRole(role);
				user.setPassword(EncryptionMD5.md5.encodePassword(
						DEFAULT_PASSWORD, loginName));
				this.usersDao.addUser(user);
				LoggerUtil.LogInfo("增加用户:"+user.getLoginName());
				out.print("{\"result\":true}");
				out.flush();
				out.close();
			}else{
				user = this.usersDao.getUserByID(Integer.parseInt(id));
				user.setCreatedAt(new Date());
				user.setUpdatedAt(new Date());
				user.setFullName(fullName);
				user.setRole(role);
				this.usersDao.updateUser(user);
				LoggerUtil.LogInfo("更新用户:"+user.getLoginName());
				out.print("{\"result\":true}");
				out.flush();
				out.close();
			}
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	
	public void editUser(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			int id = Integer.parseInt((request.getParameter("id")));
			String loginName = String.valueOf(request.getParameter("loginName"));
			String fullName = String.valueOf(request.getParameter("fullName"));
			String role = String.valueOf(request.getParameter("role"));
			if(role.equals("一般用户")){
				role = "ROLE_USER";
			}else{
				role = "ROLE_ADMIN";
			}
			Users user = this.usersDao.getUserByID(id);
			user.setCreatedAt(new Date());
			user.setUpdatedAt(new Date());
			user.setFullName(fullName);
			user.setRole(role);
			this.usersDao.updateUser(user);
			LoggerUtil.LogInfo("更新用户:"+user.getLoginName());
			out.print("{\"result\":true}");
			out.flush();
			out.close();

		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	
	public void changePassword(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			String loginName = String.valueOf(ActionContext.getContext().getSession().get("username"));
			String oldPassword = String.valueOf(request.getParameter("oldPassword"));
			String newPassword = String.valueOf(request.getParameter("newPassword"));
			Users user = this.usersDao.getUserByName(loginName);
			if(user.getPassword().equals(EncryptionMD5.md5.encodePassword(
					oldPassword, loginName))){
				user.setUpdatedAt(new Date());
				user.setPassword(EncryptionMD5.md5.encodePassword(
					newPassword, loginName));
				this.usersDao.updateUser(user);
				LoggerUtil.LogInfo(user.getLoginName()+" 的密码已经被更新");
				//System.out.print("修改成功");
				out.print("{\"result\":true}");
				out.flush();
				out.close();
			}else{
				//System.out.print("原密码不一样");
				out.print("{\"result\":3}");
				out.flush();
				out.close();
			}
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
}
